/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.type.classreading;

import java.io.IOException;
import java.util.Map;

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.util.ConcurrentReferenceHashMap;

/**
 * {@link MetadataReaderFactory} 接口的缓存实现，基于 {@link ConcurrentReferenceHashMap}，
 * 针对每个 Spring {@link Resource} 句柄（即每个 ".class" 文件）缓存 {@link MetadataReader}。
 *
 * @author Phillip Webb
 * @since 1.4.0
 * @see CachingMetadataReaderFactory
 */
public class ConcurrentReferenceCachingMetadataReaderFactory extends SimpleMetadataReaderFactory {

	private final Map<Resource, MetadataReader> cache = new ConcurrentReferenceHashMap<>();

	/**
	 * 创建一个默认类加载器的 {@link ConcurrentReferenceCachingMetadataReaderFactory} 实例。
	 */
	public ConcurrentReferenceCachingMetadataReaderFactory() {
	}

	/**
	 * 创建一个指定资源加载器的 {@link ConcurrentReferenceCachingMetadataReaderFactory} 实例。
	 * @param resourceLoader 要使用的 Spring ResourceLoader（也决定了使用的 ClassLoader）
	 */
	public ConcurrentReferenceCachingMetadataReaderFactory(ResourceLoader resourceLoader) {
		super(resourceLoader);
	}

	/**
	 * 创建一个指定类加载器的 {@link ConcurrentReferenceCachingMetadataReaderFactory} 实例。
	 * @param classLoader 要使用的 ClassLoader
	 */
	public ConcurrentReferenceCachingMetadataReaderFactory(ClassLoader classLoader) {
		super(classLoader);
	}

	@Override
	public MetadataReader getMetadataReader(Resource resource) throws IOException {
		MetadataReader metadataReader = this.cache.get(resource);
		if (metadataReader == null) {
			metadataReader = createMetadataReader(resource);
			this.cache.put(resource, metadataReader);
		}
		return metadataReader;
	}

	/**
	 * 创建元数据读取器。
	 * @param resource 源资源
	 * @return 元数据读取器
	 * @throws IOException 发生错误时抛出
	 */
	protected MetadataReader createMetadataReader(Resource resource) throws IOException {
		return super.getMetadataReader(resource);
	}

	/**
	 * 清空整个 MetadataReader 缓存，移除所有缓存的类元数据。
	 */
	public void clearCache() {
		this.cache.clear();
	}

}
